import {createHashRouter, Navigate, useLocation} from 'react-router-dom'
import Home from "../pages/home";
import Login from "../pages/login";
import Admin from "../pages/admin";
import Entry from "../pages/entry";


// 白名单路径
const WHITE_LIST = ['/login']


export const routes = createHashRouter([
    {
        path: '/login',
        element: <Login />,
    },
    {
        index: true,
        element: <Navigate to="/login" />,
    },
    {
        path: '/entry/*',
        meta: { auth: true },
        element: <AuthRoute><Entry /></AuthRoute> ,
        children: [
            { path: 'home', element: <Home /> },
            { path: 'admin', element: <Admin /> },
            { index: true, element: <Navigate to="home" /> },
            { path: '*', element: <Navigate to="/404" /> }
        ]
    },
    {
        path: '*',
        element: <Navigate to="/404" />
    }
]);

// 路由守卫组件
function AuthRoute({ children }) {
    const location = useLocation();
    // 替换为实际的登录状态检查，例如从redux、context或localStorage获取
    const isLogin = localStorage.getItem('token') !== null;

    // 如果在白名单中直接放行
    if (WHITE_LIST.includes(location.pathname)) {
        return children;
    }

    // 不在白名单但已登录，放行
    if (isLogin) {
        return children;
    }

    // 否则重定向到登录页，并携带来源路径以便登录后跳转
    return <Navigate to="/login" state={{ from: location }} replace />;
}